<?php
class Uploader
{
    public function __construct()
    {
    }

    private function getUserId()
    {
        $email = DataBase::getInstance()->quote( $_SESSION['login'] );
        
        $query = DataBaseProvider::selectUserById( $email );
        $selectResult = DataBase::getInstance()->query( $query );
        if ( !$selectResult )
        {
            throw new Exception( 'This user does not exist!' );
        }
        
        $userId = $selectResult[0]['user_id'];
        return (int)$userId;
    }

    private function isAlreadyUploaded( $fileName )
    {
        $query = DataBaseProvider::isFileAlreadyUploaded( $fileName );
        $file = DataBase::getInstance()->query( $query );
        if ( empty( $file ) )
        {
            return false;
        }
        return true;
    }

    private function insertRecordIntoDatabase( $userId, $fileName )
    {
        $fileName = DataBase::getInstance()->quote( $fileName );
        if ( $this->isAlreadyUploaded( $fileName ) )
        {
            throw new Exception( 'This file is already exist.' );
        }
        $query = DataBaseProvider::insertUploadRecordIntoDb( $fileName, $userId );
        $isInserted = DataBase::getInstance()->query( $query );
        return $isInserted;
    }
    
    /**
     * The method upload file to server and insert record about it in database.
     * 
     * @throw Exception     If the upload failed, or did not insert a record into
     *                      the database, an exception is thrown.
     * 
     * @return string - html code, with message about successful uploading.
     */
    public function uploadFile()
    {
        if ( isset( $_FILES['my_file'] ) )
        {
            $uploadedFileInfo = $_FILES['my_file'];
            $tmpFilePath  = $uploadedFileInfo['tmp_name'];
            $realFileName = $uploadedFileInfo['name'];
            $siteRoot = str_replace( 'htdocs', '', $_SERVER['DOCUMENT_ROOT'] );
            $saveFilePath =  $siteRoot . "/uploaded/" . $realFileName;
            $userId = $this->getUserId();
            if ( @move_uploaded_file( $tmpFilePath, $saveFilePath ) )
            {
                if ( $this->insertRecordIntoDatabase( $userId, $realFileName ) )
                {
                    return 'File was uploaded successfully!';
                }
                unlink( '../uploaded/' . $realFileName );
            }
        }
        throw new Exception( 'File was not uploaded!' );
    }
}
?>